#pragma once
#include <iostream>
#include <string>
#include <functional>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "netaddr.hpp"

using namespace std;

using scfunc_t = function<string(string&)>;

class Server
{
public:
    Server(scfunc_t Response, uint16_t port):_Response(Response), _port(port)
    {

    }

    void Init()
    {
        // 创建网络文件信息
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_sockfd < 0)
        {
            exit(1);
        }

        struct sockaddr_in addr;
        memset(&addr, 0, sizeof(addr));
        // addr.sin_addr.s_addr = inet_addr(_ip.c_str());
        addr.sin_addr.s_addr = INADDR_ANY;
        addr.sin_port = htons(_port);
        addr.sin_family = AF_INET;

        int n = bind(_sockfd, (struct sockaddr*)&addr, sizeof(addr));
        if(n < 0)
        {
            exit(2);
        }
    }

    void Start()
    {
        for(;;)
        {
            char buffer[1024];
            struct sockaddr_in addr;
            socklen_t len = sizeof(addr);
            // 接收客户端消息
            ssize_t n = recvfrom(_sockfd, buffer, sizeof(buffer), 0, (struct sockaddr*)&addr, &len);
            if(n > 0)
            {
                buffer[n] = 0;
                // netaddr netinfo(addr);
                string request = buffer;
                string response = _Response(request);

                n = sendto(_sockfd, response.c_str(), response.size(), 0, (struct sockaddr*)&addr, len);

                // cout << addr.sin_port << "client say# " << buffer << endl;
                // 给客户端发消息，此时addr中就有客户端主机的套接字信息
                // cout << "[" << netinfo.SockInfo() << "]" << buffer << endl;
                // n = sendto(_sockfd, buffer, sizeof(buffer), 0, (struct sockaddr*)&addr, len);
            }
        }

        close(_sockfd);
    }

    ~Server()
    {
    }

private:
    int _sockfd;
    scfunc_t _Response;
    uint16_t _port;
};